package com.xinsoft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinsoft.common.exception.BDException;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.CusPatrolDTO;
import com.xinsoft.entity.dto.CusPatrolParam;
import com.xinsoft.entity.po.*;
import com.xinsoft.entity.vo.CusPatrolDetailVo;
import com.xinsoft.entity.vo.CusPatrolDeviceVo;
import com.xinsoft.entity.vo.CusPatrolVo;
import com.xinsoft.mapper.CusPatrolMapper;
import com.xinsoft.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lijie
 * @description 针对表【cus_patrol(巡检)】的数据库操作Service实现
 * @createDate 2023-06-21 09:08:12
 */
@Service
public class CusPatrolServiceImpl extends ServiceImpl<CusPatrolMapper, CusPatrol>
        implements CusPatrolService {

    @Resource
    CusPatrolMapper cusPatrolMapper;

    @Resource
    CusPatrolDetailService detailService;

    @Resource
    SysUserService userService;

    @Resource
    SysDeptService deptService;

    @Resource
    CusDocumentPatrolService documentPatrolService;

    @Resource
    SysFileHisService fileHisService;

    @Resource
    SysDocumentNumService sysDocumentNumService;

    @Autowired
    private CusDocumentService cusDocumentService;

    @Override
    public Object findPageListByParam(CusPatrolParam param) {
        //分页
        Page<CusPatrol> page = new Page<CusPatrol>(param.getCurrentPage(), param.getPageSize());
        IPage<CusPatrol> resultPage = cusPatrolMapper.findListByParam(page, param);
        //返回值
        return resultPage;
    }

    @Override
    public CusPatrolVo getByInfoById(Integer id) {
        CusPatrol cusPatrol = cusPatrolMapper.selectById(id);
        // 组装负责人姓名，电话，部门
        SysUser user = userService.getById(cusPatrol.getPatrolPersonId());
        if (user != null) {
            cusPatrol.setPlanPersonName(user.getRealName());
            cusPatrol.setPlanPersonDept(deptService.getById(user.getDeptId()).getDeptName());
            cusPatrol.setPlanPersonTel(user.getMobile());
        }
        CusPatrolVo cusPatrolVo = new CusPatrolVo();
        BeanUtil.copyProperties(cusPatrol, cusPatrolVo);
        // 组装巡检明细
        List<CusPatrolDeviceVo> patrolDeviceVoList = cusPatrolMapper.getDeviceListByPatrolId(cusPatrolVo.getId());
        if (patrolDeviceVoList.size() > 0) {
            for (int i = 0; i < patrolDeviceVoList.size(); i++) {
                CusPatrolDeviceVo cusPatrolDeviceVo = patrolDeviceVoList.get(i);
                List<CusPatrolDetailVo> detailVoList = cusPatrolMapper.getDetailListByDeviceId(cusPatrolDeviceVo.getDeviceId(), cusPatrolVo.getId());
                if (detailVoList.size() > 0) {
                    for (int j = 0; j < detailVoList.size(); j++) {
                        //照片列表
                        QueryWrapper queryWrapper = new QueryWrapper<>();
                        queryWrapper.select("document_id");
                        queryWrapper.eq("device_ref_id",detailVoList.get(j).getPatrolStandardId());
                        queryWrapper.eq("device_ref_type",Const.DeviceRefType.PATROL_BASIC);
                        List<CusDocument> documentList = cusDocumentService.list(queryWrapper);
                        detailVoList.get(j).setCusDocumentListDocument(documentList);
                        // 图片列表
                        if(CollectionUtil.isNotEmpty(documentList)){
                            List<Integer> fileIds = documentList.stream()
                                    .map(CusDocument::getDocumentId)
                                    .collect(Collectors.toList());
                            QueryWrapper queryFileWrapper = new QueryWrapper<>();
                            queryFileWrapper.in("id",fileIds);
                            List<SysFileHis> fileHisList = fileHisService.list(queryFileWrapper);
                            detailVoList.get(j).setSysFileHisList(fileHisList);
                        }
                    }
                    cusPatrolDeviceVo.setCusPatrolDetailList(detailVoList);
                }
            }
            cusPatrolVo.setCusPatrolDeviceVoList(patrolDeviceVoList);
        }
        // 组装图片
        List<CusDocumentPatrol> list = documentPatrolService.list(new QueryWrapper<CusDocumentPatrol>().eq("patrol_id", id));
        List<Integer> fileIds = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            fileIds.add(list.get(i).getDocumentId());
        }
        if (list.size() > 0) {
            List<SysFileHis> sysFileHis = fileHisService.listByIds(fileIds);
            cusPatrolVo.setPatrolImgList(sysFileHis);
        }
        return cusPatrolVo;
    }

    @Override
    public void submit(CusPatrolDTO cusPatrolDTO) {
        // 暂存有新增和编辑场景
        if (cusPatrolDTO.getId() == null) {
            cusPatrolDTO.setPatrolStatus(Const.UPKEEP_STATUS_WAIT);
            sysDocumentNumService.incrementLastSerialByDocumentId(Const.DOCUMENT_ID.PATROL_ORDER_DOCUMENT);
            cusPatrolMapper.insert(cusPatrolDTO);
            // 解析执行设备项目关系表
            if (cusPatrolDTO.getDeviceDTOList().size() > 0) {
                this.dealOrderList(cusPatrolDTO);
            } else {
                throw new BDException("操作失败，不包含设备巡检标准集合！");
            }
            // 巡检文件操作
            this.saveDocumentPatrolList(cusPatrolDTO);
        } else {
            if (cusPatrolDTO.getDeviceDTOList().size() > 0) {
                cusPatrolDTO.setPatrolStatus(Const.UPKEEP_STATUS_WAIT);
                detailService.remove(new QueryWrapper<CusPatrolDetail>().eq("patrol_id", cusPatrolDTO.getId()));
                this.dealOrderList(cusPatrolDTO);
            } else {
                throw new BDException("操作失败，不包含设备巡检标准集合！");
            }
            cusPatrolMapper.updateById(cusPatrolDTO);
            // 巡检文件操作
            documentPatrolService.remove(new QueryWrapper<CusDocumentPatrol>().eq("patrol_id", cusPatrolDTO.getId()));
            this.saveDocumentPatrolList(cusPatrolDTO);
        }
    }

    @Override
    public void tempSave(CusPatrolDTO cusPatrolDTO) {
        // 暂存有新增和编辑场景
        if (cusPatrolDTO.getId() == null) {
            cusPatrolDTO.setPatrolStatus(Const.UPKEEP_STATUS_TEMPSAVE);
            sysDocumentNumService.incrementLastSerialByDocumentId(Const.DOCUMENT_ID.PATROL_ORDER_DOCUMENT);
            cusPatrolMapper.insert(cusPatrolDTO);
            // 解析执行设备项目关系表
            if (cusPatrolDTO.getDeviceDTOList() != null) {
                this.dealOrderList(cusPatrolDTO);
            } else {
                throw new BDException("操作失败，不包含设备巡检标准集合！");
            }
            // 巡检文件操作
            this.saveDocumentPatrolList(cusPatrolDTO);
        } else {
            if (cusPatrolDTO.getDeviceDTOList() != null) {
                cusPatrolDTO.setPatrolStatus(Const.UPKEEP_STATUS_TEMPSAVE);
                detailService.remove(new QueryWrapper<CusPatrolDetail>().eq("patrol_id", cusPatrolDTO.getId()));
                this.dealOrderList(cusPatrolDTO);
            } else {
                throw new BDException("操作失败，不包含设备巡检标准集合！");
            }
            cusPatrolMapper.updateById(cusPatrolDTO);
            // 巡检文件操作
            documentPatrolService.remove(new QueryWrapper<CusDocumentPatrol>().eq("patrol_id", cusPatrolDTO.getId()));
            this.saveDocumentPatrolList(cusPatrolDTO);
        }
    }

    @Override
    public void finish(CusPatrolDTO cusPatrolDTO) {
        // 完成没有新增场景
        if (cusPatrolDTO.getDeviceDTOList().size() > 0) {
            cusPatrolDTO.setPatrolStatus(Const.UPKEEP_STATUS_OVER);
            detailService.remove(new QueryWrapper<CusPatrolDetail>().eq("patrol_id", cusPatrolDTO.getId()));
            this.dealOrderList(cusPatrolDTO);
        } else {
            throw new BDException("操作失败，不包含设备巡检标准集合！");
        }
        cusPatrolMapper.updateById(cusPatrolDTO);
        // 巡检文件操作
        documentPatrolService.remove(new QueryWrapper<CusDocumentPatrol>().eq("patrol_id", cusPatrolDTO.getId()));
        this.saveDocumentPatrolList(cusPatrolDTO);
    }

    @Override
    public CusPatrolVo getTaskByDeviceId(Integer deviceId) {
        CusPatrolVo cusPatrolVo = new CusPatrolVo();
        List<CusPatrolDetailVo> cusPatrolList = cusPatrolMapper.getTaskByDeviceId(deviceId);
        if(cusPatrolList.size() > 1){
            throw new BDException("存在同期两条巡检执行任务,请前往PC端删除一条");
        }else{
            if(cusPatrolList.size() > 0){
                BeanUtil.copyProperties(cusPatrolList.get(0),cusPatrolVo);
            }else{
                return null;
            }
        }
        return cusPatrolVo;
    }

    private void dealOrderList(CusPatrolDTO cusPatrolDTO) {
        for (int i = 0; i < cusPatrolDTO.getDeviceDTOList().size(); i++) {
            for (int j = 0; j < cusPatrolDTO.getDeviceDTOList().get(i).getCusPatrolDetailList().size(); j++) {
                CusPatrolDetail detail = cusPatrolDTO.getDeviceDTOList().get(i).getCusPatrolDetailList().get(j);
                detail.setPatrolId(cusPatrolDTO.getId());
                detail.setDeviceId(cusPatrolDTO.getDeviceDTOList().get(i).getDeviceId());
                detail.setPatrolStandardId(cusPatrolDTO.getDeviceDTOList().get(i).getCusPatrolDetailList().get(j).getPatrolStandardId());
                // 乘积出来具体的关系条数
                detailService.save(detail);
            }
        }
    }

    private void saveDocumentPatrolList(CusPatrolDTO cusPatrolDTO) {
        if (cusPatrolDTO.getSysFileHisList() != null && cusPatrolDTO.getSysFileHisList().size() > 0) {
            List<CusDocumentPatrol> cusDocumentPatrolList = new ArrayList<>();
            for (int i = 0; i < cusPatrolDTO.getSysFileHisList().size(); i++) {
                CusDocumentPatrol cusDocumentPatrol = new CusDocumentPatrol();
                cusDocumentPatrol.setPatrolId(cusPatrolDTO.getId());
                cusDocumentPatrol.setDocumentId(cusPatrolDTO.getSysFileHisList().get(i).getId());
                cusDocumentPatrolList.add(cusDocumentPatrol);
            }
            documentPatrolService.saveBatch(cusDocumentPatrolList);
        }
    }
}




